﻿using System.Reflection;

namespace XLAction.GlobalIPReqAction
{
    /// <summary>
    /// 
    /// </summary>
    public static class IocAttribute
    {
        /// <summary>
        /// 为 IServiceCollection 添加扩展方法 AddAttribute，使用：[Service(ServiceLifetime.Transient)]
        /// </summary>
        /// <param name="services"></param>
        public static void AddAttribute(this IServiceCollection services)
        {
            // 扫描当前程序集的所有类型
            var assembly = Assembly.GetExecutingAssembly();
            var types = assembly.GetTypes();

            // 注入带有 MyCustomAttribute 特性的类
            Console.WriteLine("单独方法开始注册：\n");
            foreach (var type in types)
            {
                var attr = type.GetCustomAttribute<ServiceAttribute>();

                if (attr != null)
                {
                    var serviceType = attr.LifeTime switch
                    {
                        ServiceLifetime.Singleton => ServiceLifetime.Singleton,
                        ServiceLifetime.Scoped => ServiceLifetime.Scoped,
                        _ => ServiceLifetime.Transient,
                    };
                    services.Add(new ServiceDescriptor(type, type, serviceType));
                    //services.AddTransient(type);
                    Console.WriteLine("注册类：{0}，项目：{1}，命名空间：{2}" + "\n", type.Name, type.Assembly.GetName().Name, type.Namespace);
                }
            }
            Console.WriteLine("单独方法注册完成\n");

        }
    }
}
